package com.funteam.funmask;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.StringTokenizer;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewSwitcher;

public class AlbumActivity extends Activity implements OnClickListener{

	protected static final int SELECT_PICTURE = 0;
	
	private static final String CURRENT_POSITION = "current_position";

	// URI object which will use for searching imageSwitcher's images
	private Uri[] mUri = null;
	// ArrayList which save file name except extension
	ArrayList<String> mName;

	private ImageSwitcher mImageSwitcher = null;
	private View mOverscrollLeft, mOverscrollRight;
	private ImageButton mIbCamera, mIbGallery;
	private TextView mTvPicDate;

	private GestureDetector mGestureDetector;
  
	private int mCurrentPosition = 0;

	private Animation mSlideInLeft, mSlideOutRight, mSlideInRight, mSlideOutLeft, mOverscrollLeftFadeOut, mOverscrollRightFadeOut;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.album_view);
	    
	    //back to camera button function definition
        mIbCamera = (ImageButton) findViewById(R.id.ib_camera);
        mIbCamera.setOnClickListener(this);

        //Go to gallery button definition
        mIbGallery =(ImageButton) findViewById(R.id.ib_albumlist);
        mIbGallery.setOnClickListener(this);
        
        if (savedInstanceState != null) {
			mCurrentPosition = savedInstanceState.getInt(CURRENT_POSITION, 0);
		}

		// Views
		mImageSwitcher = (ImageSwitcher) findViewById(R.id.image_switcher);

		mOverscrollLeft = findViewById(R.id.view_overscroll_left);
		mOverscrollRight = findViewById(R.id.view_overscroll_right);

		// Animations
		mSlideInLeft = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
		mSlideOutRight = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
		mSlideInRight = AnimationUtils.loadAnimation(this, R.anim.slide_in_right);
		mSlideOutLeft = AnimationUtils.loadAnimation(this, R.anim.slide_out_left);
		mOverscrollLeftFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
		mOverscrollRightFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);

		// ImageSwitcher
		// make ImageSwitcher's ImageView
		mImageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
			public View makeView() {
				ImageView view = new ImageView(AlbumActivity.this);
				
				view.setImageBitmap(null);
				view.setImageURI(null);
				view.setScaleType(ImageView.ScaleType.CENTER_CROP);
				view.setLayoutParams(new ImageSwitcher.LayoutParams(
						ViewGroup.LayoutParams.MATCH_PARENT,
						ViewGroup.LayoutParams.MATCH_PARENT));

				return view;
			}		 

		});
		

		// pick image filter "jpg" file which put each image
		class ImageFilter implements FilenameFilter {
			public boolean accept(File dir, String name) {
				return (name.endsWith(".jpg"));
			}
		}
		
		
		File images = new File("/mnt/sdcard/FUNMASK/");
		// bring image files and put file objects in image list
		File[] imagelist = images.listFiles(new ImageFilter());
		String[] mFiles = new String[imagelist.length];
		mName = new ArrayList<String>();
		
		for(int i = 0; i < imagelist.length; i++) {
			// put Image's absolute path in array
			mFiles[i] = imagelist[i].getAbsolutePath();
			StringTokenizer stok = new StringTokenizer(imagelist[i].getName(),".");
			// pick file names
			mName.add(stok.nextToken());
		}
	
		mUri = new Uri[mFiles.length];
		for(int i = 0; i < mFiles.length; i++) {
			mUri[i] = Uri.parse(mFiles[i]);
		}
	
		mImageSwitcher.setImageURI(mUri[mCurrentPosition]);
		
		// TextView which shows photo file's name
		mTvPicDate = (TextView)this.findViewById(R.id.tv_pic_date);
		mTvPicDate.setText(mUri[mCurrentPosition].toString().substring(20, 37));
//		mTvPicDate.setText(mUri[mCurrentPosition].toString());
//		mTvPicDate.setSelected(true);
		
		
		mGestureDetector = new GestureDetector(this, new SwipeListener());
		mImageSwitcher.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				mGestureDetector.onTouchEvent(event);
				return true;
			}
		});
		
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (outState == null) {
			return;
		}
		outState.putInt(CURRENT_POSITION, mCurrentPosition);
	}

	private void moveNextOrPrevious(int delta) {
		
		int nextImagePos = mCurrentPosition + delta;
		if (nextImagePos < 0) {
			mOverscrollLeft.setVisibility(View.VISIBLE);
			mOverscrollLeft.startAnimation(mOverscrollLeftFadeOut);
			return;
		}
		
		if (nextImagePos >= mUri.length) {
			mOverscrollRight.setVisibility(View.VISIBLE);
			mOverscrollRight.startAnimation(mOverscrollRightFadeOut);
			return;
		}

		mImageSwitcher.setInAnimation(delta > 0 ? mSlideInRight : mSlideInLeft);
		mImageSwitcher.setOutAnimation(delta > 0 ? mSlideOutLeft : mSlideOutRight);

		mCurrentPosition = nextImagePos;

		mImageSwitcher.setImageDrawable(null);
		mImageSwitcher.setImageURI(null);
		mImageSwitcher.setImageURI(mUri[mCurrentPosition]);
		
		//TextView which shows photo file's name
		mTvPicDate.setText(mUri[mCurrentPosition].toString().subSequence(20, 37));
	}

	private class SwipeListener extends SimpleOnGestureListener {
		private static final int SWIPE_MIN_DISTANCE = 75;
		private static final int SWIPE_MAX_OFF_PATH = 250;
		private static final int SWIPE_THRESHOLD_VELOCITY = 200;

		@Override
	    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
        float velocityY) {
			try {
				if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
					return false;
				// right to left swipe
				if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					moveNextOrPrevious(1);
				} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					moveNextOrPrevious(-1);
				}
			} catch (Exception e) {
				
			}
			return false;
    }
  }

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		
		case R.id.ib_camera:
			Intent intent= new Intent(AlbumActivity.this, FunMaskActivity.class);	
			startActivity(intent);
			finish();
			break;
		case R.id.ib_albumlist:
			Intent intent1 = new Intent(); 
            intent1.setType("image/*"); 
            intent1.setAction(Intent.ACTION_GET_CONTENT); 
            startActivityForResult(Intent.createChooser(intent1, "Select Picture"), SELECT_PICTURE); 
			break;
		}
	}
	
	
	// bottom menu definition
	/*public boolean onCreateOptionsMenu(Menu menu){
		
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0,1,0, "Share").setIcon(R.drawable.sharebutton);
		menu.add(0,2,0, "Delete").setIcon(R.drawable.deletebutton);
		return result;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch(item.getItemId()) {
		// share menu
		case 1:

			Intent intent1 = new Intent(Intent.ACTION_SEND);
			intent1.setType("image/*");
			String path1 = mUri[mCurrentPosition].toString();
			intent1.putExtra(Intent.EXTRA_STREAM, Uri.parse(path1));
			intent1.putExtra(Intent.EXTRA_SUBJECT, Uri.parse(path1));
	        startActivity(intent1);
			
            return true;
            
        // delete menu
		case 2:
			AlertDialog.Builder alert = new AlertDialog.Builder(AlbumActivity.this);
    		
    		alert.setTitle("Delete Confirm");
			alert.setMessage("Are you sure you want to delete this photo?");
			alert.setIcon(R.drawable.ic_launcher);
			alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {

					// bring current image that shows in imageSwitcher
					String path = null;
					path = mUri[mCurrentPosition].toString();
					File file = new File(path);
					
					String[] filePathColumn = { MediaColumns.DATA };
	        		Cursor cursor = null;
	    			cursor = getContentResolver().query(
	        				Images.Media.EXTERNAL_CONTENT_URI, filePathColumn,
	        				"bucket_display_name='FUNMASK'", null, null);
					
	    			// if folder has just one image
					if(cursor.getCount() == 1) {
						
						file.delete(); 
						
						Intent intent = new Intent(AlbumActivity.this,
								FunMaskActivity.class);
	        			startActivity(intent);
	        			
					} else {
						
						file.delete(); 
						
						Intent refresh = new Intent(AlbumActivity.this, AlbumActivity.class); 
						startActivity(refresh);
						AlbumActivity.this.finish();
					}
					
					Toast.makeText(getApplicationContext(), "Deleted photo.", Toast.LENGTH_SHORT).show();
					
				}
			
			});
			
			alert.setNegativeButton("No", null);
			alert.show();
			
			break;
		
		}
		return true;
	}*/

	
}
